package com.steel.yfmall.cloud.assistant.contract.impl;

import com.alibaba.fastjson.JSON;
import com.steel.yfmall.cloud.assistant.contract.ContractBaseService;
import com.steel.yfmall.cloud.assistant.dto.para.contract.ParaAccountFramewordBean;
import com.steel.yfmall.cloud.assistant.dto.para.contract.ParaContractBaseBean;
import com.steel.yfmall.cloud.assistant.dto.para.contract.ParaFrameworkContractInfoBean;
import com.steel.yfmall.cloud.assistant.dto.para.goods.ParaProductSellerGoodsBean;
import com.steel.yfmall.cloud.assistant.dto.result.goods.ResultProductSellerGoodsBean;
import com.steel.yfmall.cloud.assistant.goods.*;
import com.steel.yfmall.cloud.assistant.goods.mapper.FrameworkContractInfoMapper;
import com.steel.yfmall.cloud.assistant.goods.mapper.FrameworkContractUserAccountMapper;
import com.steel.yfmall.cloud.assistant.goods.mapper.ProductLibBrandMapper;
import com.steel.yfmall.cloud.assistant.po.goods.*;
import com.steel.yfmall.cloud.components.utils.base.APIMsgBean;
import com.steel.yfmall.cloud.product.bean.enums.EnumsContractType;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@Service
@Slf4j
public class ContractBaseServiceImpl implements ContractBaseService {


    @Resource
    private ProductSellerGoodsService productSellerGoodsService;

    @Resource
    private ProductLibBrandMapper productLibBrandMapper;

    @Resource
    private FrameworkContractGoodsInfoService goodsInfoService;

    @Resource
    private FrameworkContractInfoService contractInfoService;

    @Resource
    private FrameworkContractAddressInfoService addressInfoService;

    @Resource
    private FrameworkContractRegionService regionService;

    @Resource
    private FrameworkContractUserAccountMapper frameworkContractUserAccountMapper;

    @Resource
    private FrameworkContractInfoMapper frameworkContractInfoMapper;

    @Override
    public APIMsgBean<Boolean> contractInfo(ParaContractBaseBean paraContractBaseBean) {
        APIMsgBean<Boolean> booleanAPIMsgBean = new APIMsgBean<>();
        FrameworkContractAddressInfo addressInfo = null;
        FrameworkContractInfo contractInfo = null;
        FrameworkContractGoodsInfo ginfo = null;
        if (paraContractBaseBean == null) {
            booleanAPIMsgBean.setData(false);
            booleanAPIMsgBean.getSoaStateBean().setMessage("参数异常，状态不能为空");
            return booleanAPIMsgBean;
        }
        try {
            //更新合同主档
            ParaContractBaseBean.ContractInfo ContractInfo = paraContractBaseBean.getContract();
            contractInfo = contractInfo(ContractInfo);
            if (contractInfoService.update(contractInfo) <= 0) {
                contractInfoService.insert(contractInfo);
            }
            //更新地址档
            ParaContractBaseBean.AddressInfo ainfo = paraContractBaseBean.getAddress();
            addressInfo = addressInfo(ainfo, contractInfo);
            int up0 = addressInfoService.update(addressInfo);
            if (up0 <= 0) {
                addressInfoService.insert(addressInfo);
            }
            //增加终到地区、终到地点
            List<ParaContractBaseBean.ContractRegion> regions = paraContractBaseBean.getRegions();
            //删除原有数据
            FrameworkContractRegionExample rexample = new FrameworkContractRegionExample();
            FrameworkContractRegionExample.Criteria rcriteria = rexample.createCriteria();
            rcriteria.andCommerceContractNoEqualTo(contractInfo.getContractNo());
            regionService.delete(rexample);
            for (ParaContractBaseBean.ContractRegion region : regions) {
                FrameworkContractRegion fregion = GetRegion(region);
                regionService.insert(fregion);
            }
            //更新物料明细档
            List<ParaContractBaseBean.GoodsInfo> goodInfos = paraContractBaseBean.getGoods();


            ParaProductSellerGoodsBean paraProductSellerGoodsBean = null;

            FrameworkContractGoodsInfoExample example = new FrameworkContractGoodsInfoExample();
            FrameworkContractGoodsInfoExample.Criteria criteria = example.createCriteria();
            criteria.andCommerceContractNoEqualTo(contractInfo.getCommerceContractNo());
            goodsInfoService.delete(example);
            for (ParaContractBaseBean.GoodsInfo good : goodInfos) {
                ginfo = goodsInfo(good, ContractInfo);
                if (ContractInfo.getProdClass().equals("H") && EnumsContractType.S.getContractTypeCode().equals(ContractInfo.getContractNewType()) || EnumsContractType.J.getContractTypeCode().equals(ContractInfo.getContractNewType())) {
                    //拼接查询商品表参数
                    paraProductSellerGoodsBean = joinSellerInfo(good, ContractInfo);
                    ResultProductSellerGoodsBean resultProductSellerGoodsBean = productSellerGoodsService.getSellerGoodsProductSysCodeBySite(paraProductSellerGoodsBean);
                    if (resultProductSellerGoodsBean != null) {
                        ginfo.setProductSysCode(resultProductSellerGoodsBean.getProductSysCode());
                    }
                }
                goodsInfoService.insert(ginfo);
            }

            booleanAPIMsgBean.setData(true);
            booleanAPIMsgBean.getSoaStateBean().setMessage("更新合同成功！合同号" + contractInfo.getContractNo() + ",物料更新size=" + goodInfos.size());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return booleanAPIMsgBean;
    }

    /**
     * 苍穹同步合同关联资金账户信息到电商，单条同步
     *
     * @param paraAccountFramewordBean
     * @return
     */
    @Override
    public APIMsgBean<Boolean> pushAccountFrameword(ParaAccountFramewordBean paraAccountFramewordBean) {
        log.info("pushAccountFrameword请求参数 " + JSON.toJSONString(paraAccountFramewordBean));
        APIMsgBean<Boolean> apiMsgBean = new APIMsgBean<>();
        if (paraAccountFramewordBean == null
                || StringUtils.isBlank(paraAccountFramewordBean.getCommerceContractNo())
                || StringUtils.isBlank(paraAccountFramewordBean.getAccountCode())
                || StringUtils.isBlank(paraAccountFramewordBean.getCompanyName())
                || StringUtils.isBlank(paraAccountFramewordBean.getErpCompanyCode())
                || paraAccountFramewordBean.getStatus() == null) {
            apiMsgBean.getSoaStateBean().setMessage("参数错误！");
            return apiMsgBean;
        }
        try {
            //根据 合同号+资金账户号码+公司别名+ erp客户编码 确定唯一
            FrameworkContractUserAccountExample frameworkContractUserAccountExample = new FrameworkContractUserAccountExample();
            frameworkContractUserAccountExample.createCriteria()
                    .andCommerceContractNoEqualTo(paraAccountFramewordBean.getCommerceContractNo())
                    .andAccountCodeEqualTo(paraAccountFramewordBean.getAccountCode())
                    .andCompanyNameEqualTo(paraAccountFramewordBean.getCompanyName())
                    .andErpCompanyCodeEqualTo(paraAccountFramewordBean.getErpCompanyCode());
            FrameworkContractUserAccount frameworkContractUserAccount = frameworkContractUserAccountMapper.selectOneByExampleSelective(frameworkContractUserAccountExample);
            if (frameworkContractUserAccount == null) {
                //新增
                FrameworkContractUserAccount record = new FrameworkContractUserAccount();
                record.setCommerceContractNo(paraAccountFramewordBean.getCommerceContractNo());
                record.setAccountCode(paraAccountFramewordBean.getAccountCode());
                record.setCompanyName(paraAccountFramewordBean.getCompanyName());
                record.setErpCompanyCode(paraAccountFramewordBean.getErpCompanyCode());
                record.setStatus(0);
                frameworkContractUserAccountMapper.insertSelective(record);
            } else {
                //修改状态
                FrameworkContractUserAccount record = new FrameworkContractUserAccount();
                record.setId(frameworkContractUserAccount.getId());
                record.setStatus(paraAccountFramewordBean.getStatus());
                frameworkContractUserAccountMapper.updateByPrimaryKeySelective(record);
            }
        } catch (Exception e) {
            log.info("pushAccountFrameword异常，参数 " + JSON.toJSONString(paraAccountFramewordBean) + "异常：" + e.getMessage());
            return apiMsgBean;
        }
        apiMsgBean.getSoaStateBean().setCode(1);
        apiMsgBean.getSoaStateBean().setMessage("成功");
        return apiMsgBean;
    }

    /**
     * 苍穹推送电商合同状态变更接口
     *
     * @param paraFrameworkContractInfoBean
     * @return
     */
    @Override
    public APIMsgBean<Boolean> closeFrameworkContractInfo(ParaFrameworkContractInfoBean paraFrameworkContractInfoBean) {
        log.info("接口closeFrameworkContractInfo,参数：" + JSON.toJSONString(paraFrameworkContractInfoBean));
        APIMsgBean<Boolean> apiMsgBean = new APIMsgBean<>();
        if (paraFrameworkContractInfoBean == null) {
            apiMsgBean.getSoaStateBean().setMessage("参数不能为空！");
        }
        if (StringUtils.isBlank(paraFrameworkContractInfoBean.getCommerceContractNo())) {
            apiMsgBean.getSoaStateBean().setMessage("合同号不能为空");
        }
        Integer contractStatus = paraFrameworkContractInfoBean.getContractStatus();
        if (contractStatus == null || (contractStatus != 2 && contractStatus != 4)) {
            apiMsgBean.getSoaStateBean().setMessage("合同状态不能为空，且只能是待审核与关闭");
        }
        FrameworkContractInfo record = new FrameworkContractInfo();
        record.setContractStatus(contractStatus);
        FrameworkContractInfoExample example = new FrameworkContractInfoExample();
        example.createCriteria().andCommerceContractNoEqualTo(paraFrameworkContractInfoBean.getCommerceContractNo());
        int i = frameworkContractInfoMapper.updateByExampleSelective(record, example);
        if (i > 0) {
            apiMsgBean.getSoaStateBean().setCode(1);
            apiMsgBean.getSoaStateBean().setMessage("修改成功");
            apiMsgBean.setData(true);
            return apiMsgBean;
        }
        return apiMsgBean;
    }

    private FrameworkContractAddressInfo addressInfo(ParaContractBaseBean.AddressInfo addressInfo, FrameworkContractInfo contractInfo) {
        FrameworkContractAddressInfo finfo = new FrameworkContractAddressInfo();
        finfo.setAddressName(addressInfo.getAddressName());
//        finfo.setEndArea(addressInfo.getEndArea());
//        finfo.setEndNo(addressInfo.getEndNo());
        finfo.setSettlementTicket(addressInfo.getSettlementTicket());
        finfo.setCommerceContractNo(contractInfo.getCommerceContractNo());
        finfo.setConsignee(addressInfo.getConsignee());
        return finfo;
    }

    private FrameworkContractRegion GetRegion(ParaContractBaseBean.ContractRegion region) {
        FrameworkContractRegion info = new FrameworkContractRegion();
        info.setCommerceContractNo(region.getContractNo());
        info.setStorageCode(region.getStorageCode());
        info.setStorageType(region.getStorageType());
        info.setCreateTime(new Date());
        return info;
    }

    private FrameworkContractInfo contractInfo(ParaContractBaseBean.ContractInfo contract) {
        FrameworkContractInfo finfo = new FrameworkContractInfo();
        finfo.setContractDate(contract.getContractDate());
        finfo.setContractNo(contract.getContractNo());
        finfo.setContractVer(contract.getContractVer());
        finfo.setContractType(contract.getContractNewType());
        finfo.setContractEndDate(contract.getContractEndDate());
        finfo.setCommerceContractNo(contract.getContractNo());
        finfo.setTotalFee(contract.getTotalFee());
        finfo.setCustNo(contract.getCustomer());
        finfo.setProdClass(contract.getProdClass());
        finfo.setSignedSite(contract.getSignedSite());
        finfo.setPriceMethod(contract.getPayMethod());
        finfo.setPayMethod(contract.getPayMethod());
        finfo.setSettleTerm(contract.getSettletype());
        finfo.setOrg(contract.getOrg());
        finfo.setCurrency(contract.getCurrency());
        finfo.setExchangeRate(contract.getExchangeRate());
        finfo.setDeliveryTolerance2(contract.getDeliveryTolerance2());
        finfo.setTotalAmount(contract.getTotalAmount());
        //finfo.setCategoryId(contract.getca);
        finfo.setPayTotalFee(contract.getTotalFee());
        finfo.setFramenum(contract.getContractNo());
        finfo.setBillstatus(contract.getBillstatus());
        finfo.setSettlecustomer(contract.getSettlecustomer());
        finfo.setPayingcustomer(contract.getPayingcustomer());
        finfo.setPayty1st(contract.getPayty1st());
        finfo.setPhone1st(contract.getPhone1st());
        finfo.setPhone2nd(contract.getPhone2nd());
        finfo.setParty2nd(contract.getParty2nd());
        finfo.setPartc(contract.getPartc());
        finfo.setRemoteStorage(contract.getRemoteStorage());
        finfo.setEndUser(contract.getEndUser());
        finfo.setIsPricepolicy(contract.getIsPricepolicy());
        finfo.setAddTime(new Date());
        finfo.setMemo(contract.getMemo());
        finfo.setUpdateTime(new Date());
        if ("L1".equals(contract.getContractContparties())) {
            finfo.setContractContparties("LG");
        } else {
            finfo.setContractContparties(contract.getContractContparties());
        }
        finfo.setContractTemplate(contract.getContractTemplate());
        finfo.setContractConmprop(contract.getContractConmprop());
        finfo.setBizmode(contract.getBizmode());
        finfo.setCantractBiztime(contract.getCantractBiztime());
        finfo.setContactperson1st(contract.getContactperson1st());
        finfo.setContactperson2nd(contract.getContactperson2nd());
        finfo.setContractName(contract.getContractName());
        finfo.setContractSpecies(contract.getContractSpecies());
        finfo.setCustomer(contract.getCustomer());
        finfo.setSettletype(contract.getSettletype());
        finfo.setInputcode(contract.getInputcode());
        finfo.setContractNewType(contract.getContractNewType());
        finfo.setTotalWeight(contract.getTotalWeight());
        finfo.setTypeOfContract(contract.getTypeOfContract());
        return finfo;
    }

    private FrameworkContractGoodsInfo goodsInfo(ParaContractBaseBean.GoodsInfo goodsInfo, ParaContractBaseBean.ContractInfo contract) {
        FrameworkContractGoodsInfo finfo = new FrameworkContractGoodsInfo();
        finfo.setMaterial(goodsInfo.getMaterial());
        finfo.setCategoryId(goodsInfo.getCategoryId());
        finfo.setOrderFLength(goodsInfo.getOrderLength());
        finfo.setOrderFThick(goodsInfo.getOrderThick());
        finfo.setCommerceContractNo(contract.getContractNo());
        finfo.setProdPrice(goodsInfo.getProdPrice());
        finfo.setContractQty(goodsInfo.getContractQty());
        finfo.setBrandId(goodsInfo.getBrandId());
        finfo.setSizePieces(goodsInfo.getSizePieces());
        finfo.setIsDowngrade(goodsInfo.getIsDowngrade());
        finfo.setColor(goodsInfo.getColor());
        finfo.setProductFromCode(goodsInfo.getCategoryId());
        finfo.setProductCategorySalesCode(contract.getProdClass());
        finfo.setOrderThick(String.valueOf(goodsInfo.getOrderThick()));
        finfo.setOrderLength(goodsInfo.getOrderLength());
        finfo.setOrderWidth(0.0);
        finfo.setGoodsPrice(goodsInfo.getProdPrice());
        finfo.setCraft(goodsInfo.getCraft());
        finfo.setRuleInfo(goodsInfo.getSize());
        finfo.setCountWgtMode(contract.getWgtMode());
        finfo.setProductGrade(goodsInfo.getQualityType());
        finfo.setQuality(goodsInfo.getQualityType());
        finfo.setTransWayNo(contract.getTransType());
        finfo.setDepotCode(goodsInfo.getMaterHome());
        finfo.setCqProductSysCode(goodsInfo.getCqProductSysCode());
        return finfo;
    }

    private ParaProductSellerGoodsBean joinSellerInfo(ParaContractBaseBean.GoodsInfo goodsInfo, ParaContractBaseBean.ContractInfo contract) {
        ParaProductSellerGoodsBean paraProductSellerGoodsBean = new ParaProductSellerGoodsBean();
        paraProductSellerGoodsBean.setProductTypeNo(goodsInfo.getCategoryId());
        paraProductSellerGoodsBean.setProductTradeno(goodsInfo.getMaterial());
        paraProductSellerGoodsBean.setSizeInformation(goodsInfo.getSize());
        paraProductSellerGoodsBean.setCountWgtMode(contract.getWgtMode());
        paraProductSellerGoodsBean.setSizePieces(NumberUtils.toInt(goodsInfo.getSizePieces()));
        ProductLibBrandExample brandExample = new ProductLibBrandExample();
        brandExample.or().andBrandCodeEqualTo(goodsInfo.getBrandId());
        List<ProductLibBrand> brandList = productLibBrandMapper.selectByExample(brandExample);
        if (brandList != null && !CollectionUtils.isEmpty(brandList)) {
            paraProductSellerGoodsBean.setBrandId(brandList.get(0).getBrandId());
        }
        paraProductSellerGoodsBean.setColor(goodsInfo.getColor());
        paraProductSellerGoodsBean.setIsDowngrade(goodsInfo.getIsDowngrade());
        paraProductSellerGoodsBean.setProductGrade(goodsInfo.getQualityType());
        paraProductSellerGoodsBean.setProdClass(contract.getProdClass());
        paraProductSellerGoodsBean.setProductThick(goodsInfo.getOrderThick());
        paraProductSellerGoodsBean.setProductLen(BigDecimal.valueOf(goodsInfo.getOrderLength()));
        paraProductSellerGoodsBean.setProductWidth(BigDecimal.valueOf(0.0));
        paraProductSellerGoodsBean.setCraft(NumberUtils.toInt(goodsInfo.getCraft()));
        paraProductSellerGoodsBean.setTransWayNo(contract.getTransType());
        paraProductSellerGoodsBean.setDepotCode(goodsInfo.getMaterHome());
        return paraProductSellerGoodsBean;
    }

}
